﻿using System;
using System.Collections.Generic;
using System.Text;

namespace LeetcodeTest._100._10
{
    class Leetcode2
    {

        /*
         2. Add Two Numbers

        You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
         */
        public ListNode AddTwoNumbers(ListNode l1, ListNode l2)
        {
            ListNode listNode = new ListNode(0);
            ListNode temp = listNode;
            int tempValue = 0;
            int index = 0;
            bool l2IsNull = false;
            do
            {
                if (index == 0)
                {
                    temp = new ListNode(tempValue);
                    listNode = temp;
                }
                else
                {
                    temp.next = new ListNode(tempValue);
                    temp = temp.next;
                }
                index++;
                if (l2 == null)
                {
                    l2IsNull = true;
                    temp.val = l1.val + temp.val;
                }
                else
                {
                    temp.val = l1.val + l2.val + temp.val;
                }

                tempValue = temp.val / 10;
                temp.val = temp.val % 10;

                l1 = l1.next;
                if (!l2IsNull)
                    l2 = l2.next;
            } while (l1 != null);

            if (!l2IsNull && l2 != null)
            {
                do
                {
                    temp.next = new ListNode(tempValue);
                    temp = temp.next;
                    temp.val = l2.val + temp.val;
                    tempValue = temp.val / 10;
                    temp.val = temp.val % 10;
                    l2 = l2.next;
                } while (l2 != null);

                if (tempValue > 0)
                {
                    temp.next = new ListNode(tempValue);

                }
            }
            else if (tempValue > 0)
            {
                temp.next = new ListNode(tempValue);

            }
            return listNode;
        }
    }
     public class ListNode
    {
      public int val;
      public ListNode next;
      public ListNode(int x) { val = x; }
  }
}
